from quant_researcher.quant.project_tool.time_tool import get_today, str_to_timestamp, calc_date_diff, date_shifter
from quant_researcher.quant.datasource_fetch.crypto_api.binance import fetch_binance_kline
import os
import pandas as pd
from utils import df_into_db


# 从binance获取币安BTC兑稳定币的相关现货交易额
DATA_DIR = f'E:\\指标数据'  # 用于存放测试数据

file_path = os.path.join(DATA_DIR, r'trading_data')

end_date = get_today(marker='with_n_dash')
file_name = os.path.join(file_path, f'cex_total_spot_amount_biance_BTCUSD')
if os.path.exists(f'{file_name}.xlsx'):
    history_binance_amount = pd.read_excel(f'{file_name}.xlsx', index_col='date')
    start_date = history_binance_amount.index[-1]
    if calc_date_diff(start_date, end_date) < 3:
        start_date = date_shifter(before=start_date, step='days', how_many=-3)
else:
    start_date = '2017-01-01'
start = str_to_timestamp(start_date, tz_str='+0800')
end = str_to_timestamp(end_date, tz_str='+0800')
binance_BTCUSDT = fetch_binance_kline("BTCUSDT", start, end, '1d')
print('从binance获取BTCUSDT交易额成功')
# binance_BTCBUSD = fetch_binance_kline("BTCBUSD", start, end, '1d')
# print('从binance获取BTCBUSD交易额成功')
binance_BTCUSDC = fetch_binance_kline("BTCUSDC", start, end, '1d')
print('从binance获取BTCUSDC交易额成功')
# binance_BTCBUSD = pd.Series(binance_BTCBUSD['amount'], index=binance_BTCUSDT.index).fillna(0)
if binance_BTCUSDC is not None:
    binance_BTCUSDC = pd.Series(binance_BTCUSDC['amount'], index=binance_BTCUSDT.index).fillna(0)
    # amount = binance_BTCUSDT['amount'] + binance_BTCBUSD + binance_BTCUSDC
    amount = binance_BTCUSDT['amount'] + binance_BTCUSDC
else:
    # amount = binance_BTCUSDT['amount'] + binance_BTCBUSD
    amount = binance_BTCUSDT['amount']

amount_df = pd.DataFrame(amount)

if os.path.exists(f'{file_name}.xlsx'):
    previous_date = date_shifter(amount.index[0], step='days', how_many=-1)
    amount_df = pd.concat([history_binance_amount.loc[:previous_date, ], amount_df.iloc[:, ]])  # 最新一天数据为当天，数据还不完整
# amount_df.to_excel(f'{file_name}.xlsx')
amount_df = amount_df.reset_index(drop=False)
df_into_db(amount_df, db_name="trading_data", table_name="cex_total_spot_amount_biance_BTCUSD")